<template>
  <div class="consultation-manage">
    <!-- 标题 -->
    <div class="title">咨询过程管理</div>

    <!-- 标签栏 -->
    <el-tabs v-model="activeTab" class="tab-header" @tab-click="handleTabClick">
      <el-tab-pane label="未安排人数(356)" name="unarranged"></el-tab-pane>
      <el-tab-pane label="正常到访(356)" name="normal"></el-tab-pane>
      <el-tab-pane label="迟到(24)" name="late"></el-tab-pane>
      <el-tab-pane label="请假(24)" name="leave"></el-tab-pane>
      <el-tab-pane label="脱落(24)" name="dropout"></el-tab-pane>
    </el-tabs>

    <!-- 查询区域 -->
    <div class="search-bar">
      <div class="priority-filter">
        <el-select
          v-model="priority"
          placeholder="请选择咨询优先级"
          class="search-select"
        >
          <el-option
            v-for="item in priorityOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-button type="primary" @click="handlePriorityFilter">筛选结果</el-button>
      </div>
      <el-input
        v-model="searchKey"
        placeholder="请输入学生姓名/账号/学号/联系电话关键词查询"
        class="search-input"
        clearable
      />
      <el-button type="primary" @click="handleSearch">查询</el-button>
      <el-button @click="handleReset">重置</el-button>
    </div>

    <!-- 表格区域 -->
    <el-table
      ref="tableRef"
      :data="paginatedData"
      border
      style="width: 100%"
      class="consultation-table"
      header-cell-class-name="table-header"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="index" label="序号" width="70" />
      <el-table-column prop="studentName" label="学生姓名">
        <template #default="scope">
          <span
            :class="{
              warning: scope.row.warning,
              'hover-effect': true,
              'name-highlight': isHovering.value === scope.row.studentName
            }"
            @mouseenter="handleMouseEnter(scope.row.studentName)"
            @mouseleave="handleMouseLeave()"
            @click="goToConsultationRecord(scope.row)"
          >
            {{ scope.row.studentName }}
            <span v-if="scope.row.warning" class="warning-tag">#严重#</span>
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="account" label="账号/学号" />
      <el-table-column prop="priority" label="咨询优先级">
        <template #default="scope">
          <span :class="priorityClass(scope.row.priority)">
            {{ scope.row.priority }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="scale1" label="心理量表1" />
      <el-table-column prop="scale2" label="心理量表2" />
      <el-table-column prop="college" label="学院" />
      <el-table-column prop="counselor" label="责任辅导员" />
      <el-table-column prop="phone" label="联系电话" />
      <el-table-column prop="reserveChannel" label="预约渠道" />
      <el-table-column label="操作" width="100">
        <template #default="scope">
          <el-button
            type="text"
            @click="handleArrange(scope.row)"
          >安排</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 批量操作和分页 -->
    <div class="bottom-bar">
      <el-button type="primary" @click="handleBatchArrange">批量安排</el-button>
      <div class="pagination-info">
        <span>总共{{ total }}个</span>
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="pageSize"
          layout="prev, pager, next"
          :total="total"
        />
      </div>
    </div>

    <!-- 安排弹窗 -->
    <el-dialog
      title="请选择到访情况"
      v-model="arrangeDialogVisible"
      width="400px"
    >
      <el-form :model="arrangeForm" label-width="100px">
        <el-form-item label="到访情况">
          <el-checkbox-group v-model="arrangeForm.visitStatus">
            <el-checkbox label="正常到访">正常到访</el-checkbox>
            <el-checkbox label="迟到">迟到</el-checkbox>
            <el-checkbox label="请假">请假</el-checkbox>
            <el-checkbox label="脱落">脱落</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="咨询结果">
          <el-radio-group v-model="arrangeForm.consultResult">
            <el-radio label="结案">结案</el-radio>
            <el-radio label="续约">续约</el-radio>
          </el-radio-group>
          <div class="result-tip">

          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="arrangeDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmitArrange">提交</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import faker from 'faker';
import { useRouter } from 'vue-router';

const router = useRouter();
const tableRef = ref(null);

// 标签栏激活项
const activeTab = ref('unarranged');
// 鼠标悬停状态
const isHovering = ref('');
// 选中的行数据
const selectedRows = ref([]);

// 鼠标进入事件
const handleMouseEnter = (studentName: string) => {
  isHovering.value = studentName;
};

// 鼠标离开事件
const handleMouseLeave = () => {
  isHovering.value = '';
};
// 查询条件
const priority = ref('');
const searchKey = ref('');
const priorityOptions = [
  { label: '即可评估', value: 'immediate' },
  { label: '尽快评估', value: 'asap' },
  { label: '优先安排', value: 'prior' },
  { label: '正常排队', value: 'normal' }
];

// 优先级排序映射（数字越小优先级越高）
const priorityOrder = {
  '即可评估': 0,
  '尽快评估': 1,
  '优先安排': 2,
  '正常排队': 3
};

// 生成模拟数据的函数
const generateMockData = (count: number) => {
  const data: any[] = [];
  for (let i = 0; i < count; i++) {
    data.push({
      index: i + 1,
      studentId: `student_${i + 1}`, // 添加学生ID
      studentName: faker.name.findName(),
      account: `100${86 + i}`,
      priority: ['即可评估', '尽快评估', '优先安排', '正常排队'][Math.floor(Math.random() * 4)],
      scale1: `${Math.floor(Math.random() * 41) + 60}分`,
      scale2: `${Math.floor(Math.random() * 41) + 60}分`,
      college: faker.company.companyName(),
      counselor: faker.name.findName(),
      phone: faker.phone.phoneNumber(),
      reserveChannel: ['线上预约', '线下预约'][Math.floor(Math.random() * 2)],
      warning: Math.random() < 0.2
    });
  }
  return data;
};

// 原始表格数据（模拟，使用函数生成更多数据）
const originalTableData = ref(generateMockData(30));
// 过滤后的数据
const filteredData = ref([...originalTableData.value]);
// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);
const total = computed(() => filteredData.value.length);
// 安排弹窗相关
const arrangeDialogVisible = ref(false);
const arrangeForm = reactive({
  visitStatus: [] as string[],
  consultResult: '结案' as '结案' | '续约'
});

// 计算分页后的数据
const paginatedData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return filteredData.value.slice(start, end);
});

// 根据优先级筛选
const handlePriorityFilter = () => {
  if (!priority.value) {
    ElMessage.warning('请先选择咨询优先级');
    return;
  }

  const selectedPriority = priorityOptions.find(
    (item) => item.value === priority.value
  )?.label;

  if (selectedPriority) {
    filteredData.value = originalTableData.value.filter(
      (item) => item.priority === selectedPriority
    );
    currentPage.value = 1;
  }
};

// 搜索（含筛选和排序）
const handleSearch = () => {
  // 1. 关键词筛选
  let filtered = originalTableData.value.filter((item) => {
    const nameMatch = item.studentName.includes(searchKey.value);
    const accountMatch = item.account.includes(searchKey.value);
    const phoneMatch = item.phone.includes(searchKey.value);
    return nameMatch || accountMatch || phoneMatch;
  });

  // 2. 优先级排序
  if (priority.value) {
    // 根据选中的优先级文本获取对应的排序值
    const selectedPriority = priorityOptions.find(
      (item) => item.value === priority.value
    )?.label;

    if (selectedPriority) {
      filtered = filtered.sort((a, b) => {
        const orderA = priorityOrder[a.priority] || 99; // 未匹配到默认排最后
        const orderB = priorityOrder[b.priority] || 99;
        return orderA - orderB;
      });
    }
  }

  // 更新过滤后的数据
  filteredData.value = filtered;
  currentPage.value = 1;
};

// 重置
const handleReset = () => {
  priority.value = '';
  searchKey.value = '';
  originalTableData.value = generateMockData(30);
  filteredData.value = [...originalTableData.value];
  currentPage.value = 1;
};

// 每页条数改变
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  currentPage.value = 1;
};

// 当前页改变
const handleCurrentChange = (val: number) => {
  currentPage.value = val;
};

// 点击标签页
const handleTabClick = (tab: any) => {
  console.log('切换到标签页：', tab.name);
  originalTableData.value = generateMockData(30);
  filteredData.value = [...originalTableData.value];
  currentPage.value = 1;
};

// 点击"安排"打开弹窗
const handleArrange = (row: any) => {
  arrangeDialogVisible.value = true;
  console.log('当前行数据：', row);
};

// 提交安排信息
const handleSubmitArrange = () => {
  ElMessageBox.confirm(
    '确认提交安排信息？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    ElMessage({
      type: 'success',
      message: '提交成功!'
    });
    arrangeDialogVisible.value = false;
    originalTableData.value = generateMockData(30);
    filteredData.value = [...originalTableData.value];
    currentPage.value = 1;
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消提交'
    });
  });
};

// 批量安排
const handleBatchArrange = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择需要安排的记录');
    return;
  }
  // 为每一行数据打开安排弹窗
  selectedRows.value.forEach(row => {
    handleArrange(row);
  });
};

// 咨询优先级样式
const priorityClass = (priority: string) => {
  const map: { [key: string]: string } = {
    '即可评估': 'priority-immediate',
    '尽快评估': 'priority-asap',
    '优先安排': 'priority-prior',
    '正常排队': 'priority-normal'
  };
  return map[priority] || '';
};

// 跳转到咨询记录页面
const goToConsultationRecord = (row: any) => {
  router.push({
    name: 'ConsultationRecord',
    params: { studentId: row.studentId },
    query: { studentData: JSON.stringify(row) } // 将当前行数据作为查询参数传递
  });
};

// 处理表格选中项变化
const handleSelectionChange = (rows) => {
  selectedRows.value = rows;
};
</script>

<style scoped lang="scss">
.consultation-manage {
  padding: 20px;
  background-color: #fff;

  .top-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;

    .user-info {
      font-size: 14px;
      color: #333;
    }

    .operation {
      button {
        margin-left: 16px;
        color: #409eff;
      }
    }
  }

  .title {
    font-size: 16px;
    font-weight: bold;
    color: #333;
    margin-bottom: 16px;
  }

  .tab-header {
    margin-bottom: 16px;
    .el-tabs__item {
      color: #333;
    }
  }

  .search-bar {
    display: flex;
    align-items: center;
    margin-bottom: 16px;

    .priority-filter {
      display: flex;
      align-items: center;
      margin-right: 10px;

      .search-select {
        width: 180px;
        margin-right: 10px;
      }
    }

    .search-input {
      width: 300px;
      margin-right: 10px;
    }
  }

  .consultation-table {
    margin-bottom: 16px;

    .table-header {
      background-color: #409eff;
      color: #fff;
    }

    .warning {
      color: #f56c6c;
    }

    .warning-tag {
      margin-left: 4px;
      color: #f56c6c;
    }

    .priority-immediate {
      color: red;
    }
    .priority-asap {
      color: orange;
    }
    .priority-prior {
      color: #409eff;
    }
    .priority-normal {
      color: green;
    }
  }

  .tips {
    color: #ff0000;
    margin-bottom: 16px;
    p {
      margin: 4px 0;
    }
  }

  .bottom-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .pagination-info {
      display: flex;
      align-items: center;

      span {
        margin-right: 10px;
        color: #666;
      }
    }
  }

  .dialog-footer {
    text-align: right;
  }

  .result-tip {
    margin-top: 8px;
    color: #ff0000;
    font-size: 12px;
  }
}
.hover-effect {
  transition: all 0.3s ease;
  cursor: pointer;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(64, 158, 255, 0.3);
  }

  &.name-highlight {
    color: #409eff;
    text-decoration: underline;
  }

  .warning {
    color: #f56c6c;
  }

  .warning-tag {
    margin-left: 4px;
    color: #f56c6c;
  }
}
</style>